import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout/index.vue'
import Myorder from '@/views/myorder'
import Pay from '@/views/pay'
import Prodetail from '@/views/prodetail'
import Search from '@/views/search/index.vue'
import SearchList from '@/views/search/list.vue'
import Home from '@/views/layout/home.vue'
import Cart from '@/views/layout/cart.vue'
import Category from '@/views/layout/category.vue'
import User from '@/views/layout/user.vue'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/cart', component: Cart },
      { path: '/category', component: Category },
      { path: '/user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/myorder', component: Myorder },
  { path: '/pay', component: Pay },
  // 动态路由传参 ，确认将来是哪个商品，路由参数中携带id
  { path: '/prodetail/:id', component: Prodetail },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList }

]

const router = new VueRouter({
  routes
})

// 定义一个数组 用于存放和权限页面
const authUrls = ['/pay', '/myorder']

// 全局前置导航守卫 导航拦截
// to: 到哪里来 到哪去的完整路由信息对象（路径，参数）
// from: 从哪里来 从哪去的完整路由信息对象（路径，参数）
// next()：是否放行
// （1） next() 直接放行到to要去的路径
// （2）next(路径)进行拦截，拦截到next配置的路径
router.beforeEach((to, from, next) => {
  // console.log(to.path, authUrls[0])
  // if(to.fullPath !==)
  // 判断是否为权限页面 非权限页面直接放还行
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 权限页面
  const token = store.getters.getToken
  console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
